<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header" id="layui-card-header-op"></div>
                <div class="layui-card-body">
                    <div class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width: 28px; margin-left: 0px;">校区</label>
                            <div class="layui-input-block" id="campus-radio" style="margin-left: 60px">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width: 28px; margin-left: 0px;">教师</label>
                            <div class="layui-input-block" lay-filter="teacher" id="teacher-radio" style="margin-left: 60px">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width: 28px; margin-left: 0px;">时间</label>
                            <div class="layui-input-block" id="time-radio" style="margin-left: 60px">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width: 28px; margin-left: 0px;"></label>
                            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="submit">确认</button>
                            <button id="screening" class="layui-btn layui-btn-sm" lay-submit lay-filter="screening" title="筛除时间冲突和人数已满课程">筛除</button>
                            <button id="refreshBtn" class="layui-btn layui-btn-sm" lay-submit lay-filter="refresh">重选</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header">人数显示</div>
                <div class="layui-card-body">
                    <div class="layui-carousel layadmin-carousel layadmin-dataview">
                        <div style="width: 100%; height:300px" id="LAY-index-dataview">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header">课程列表</div>
                <div class="layui-card-body">
                    <table class="layui-hide" id="test-table-page" lay-filter="test"></table>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="lineBar">
    <a class="layui-btn layui-btn-xs" lay-event="detail">选课页</a>
</script>
<script src="/js/controller/textSort.js"></script>
<script>
    layui.use(['jquery', 'table', "echarts", "carousel"], function(){
        var $ = layui.$, form = layui.form,
            echarts = layui.echarts, admin = layui.admin,
            view = layui.view, table = layui.table;
        var host = "";
        var classname = layui.data('choose')['className'];
        document.getElementById("layui-card-header-op").innerText = decodeURI(classname);
        var classInfoList = [];     // 校区-教师-时间列表
        var selClassInfoIndexList = [];
        var classInfoData;          // 原始课程信息
        var formatClassInfoData;    // 格式化后课程信息
        var radioIdMap = {};        // radio id记录
        var radioId = 0;
        var tableln;

        $.ajax({
            url: host + "/jw/course/public/elective/" + classname
            ,dataType: 'JSON'
            ,complete: function (result) {
                result = result.responseJSON;
                if (result['status'] === 200) {
                    classInfoData = result.data;
                    formatClassInfoData = parseClassList(classInfoData);
                    renderRadio();
                    renderTable(classInfoData);
                }
            }
        });

        // 隐藏重选按钮
        $('#refreshBtn').hide();
        
        function parseClassList(classInfos) {
            var result = [];
            for(var key in classInfos) {
                var classInfo = classInfos[key];
                var campus = classInfo["campus"];
                var teacherMap = result[campus];
                if (teacherMap === undefined) {
                    teacherMap = [];
                    result[campus] = teacherMap
                }

                var teacher = strs2Str(classInfo["teachers"]);
                var timeMap = teacherMap[teacher];
                if (timeMap === undefined) {
                    timeMap = [];
                    teacherMap[teacher] = timeMap
                }

                var classTimes = classInfo["time"];
                var timeList = [];
                for (var i = 0; i < classTimes.length; i++) {
                    timeList[i] = classTimes[i]["description"]
                }
                var time = strs2Str(timeList);
                timeMap[time] = classInfo
            }
            return result;
        }

        // 数组变为字符串
        function strs2Str(strs) {
            var s = "";
            for (var i = 0; i < strs.length; i++) {
                var str = strs[i];
                if(i < strs.length - 1) {
                    s += (str + ",")
                } else {
                    s += str
                }
            }
            return s;
        }

        function list2Str(list, key) {
            var str = "";
            var set = new Set();
            for(var i = 0; i < list.length; i++) {
                set.add(list[i][key])
            }
            set.forEach(function (data) {
                str += data + " "
            });
            return str;
        }
        
        function renderRadio() {
            // 清理工作
            $('#campus-radio').empty();
            $('#teacher-radio').empty();
            $('#time-radio').empty();
            classInfoList= [];
            radioIdMap = {};
            radioId = 0;
            var data = [];
            if(selClassInfoIndexList.length === 0) {
                data= formatClassInfoData;
            }else {
                for (var i = 0; i < selClassInfoIndexList.length; i++) {
                    var campus = selClassInfoIndexList[i][0];
                    var teacher = selClassInfoIndexList[i][1];
                    var time = selClassInfoIndexList[i][2];
                    if (data[campus] === undefined) data[campus] = [];
                    if (data[campus][teacher] === undefined) data[campus][teacher] = [];

                    data[campus][teacher][time] = formatClassInfoData[campus][teacher][time];
                }
            }
            var campusSet = new Set();
            var teacherSet = new Set();
            var timeSet = new Set();
            for(var campus in data) {
                campusSet.add(campus);
                for (var teacher in data[campus]) {
                    teacherSet.add(teacher);
                    for (var time in data[campus][teacher]) {
                        timeSet.add(time);
                        classInfoList.push([campus, teacher, time]);
                    }
                }
            }
            timeSet = new Set(Array.from(timeSet).sort(sortText));
            teacherSet = new Set(Array.from(teacherSet).sort(sortText));

            // 数量为1则选中
            for (var campus of campusSet) {
                addRadio("campus-radio", "campus", campus, campusSet.size === 1);
            }
            for (var teacher of teacherSet) {
                addRadio("teacher-radio", "teacher", teacher, teacherSet.size === 1);
            }
            for (var time of timeSet) {
                addRadio("time-radio", "time", time, timeSet.size === 1);
            }
            form.render();
            drawPersonNum(classInfoList);
        }
        function addRadio(id, name, value, checked) {
            radioIdMap[value] = "radio-" + radioId++;
            var title = value;
            if (title.length > 23) title = title.substring(0, 21) + "..";
            var html = "<input type='radio' lay-filter='filter' name=" + name + " value='" + value + "' title='" + title + "' id='" + radioIdMap[value]  + "'";
            if (checked){
                html += " checked>";
            }else {
                html += ">";
            }
            $('#' + id).append(html);
        }
        // 监听radio
        form.on('radio(filter)', function(){
            // 展示重选按钮
            $('#refreshBtn').show();

            var sel_campus = $("input[name='campus']:checked").val();
            var sel_teacher = $("input[name='teacher']:checked").val();
            var sel_time = $("input[name='time']:checked").val();
            selClassInfoIndexList = [];
            var selClassInfoList = [];
            for(var index in classInfoList) {
                var campus = classInfoList[index][0];
                if(sel_campus == null || sel_campus == campus) {
                    var teacher = classInfoList[index][1];
                    if (sel_teacher == null || sel_teacher == teacher) {
                        var time = classInfoList[index][2];
                        if (sel_time == null || sel_time == time) {
                            selClassInfoIndexList.push(classInfoList[index]);
                            selClassInfoList.push(classInfoData[index])
                        }
                    }
                }
            }
            renderTable(selClassInfoList);
            renderRadio();
        });

        // 监听提交
        form.on('submit(submit)', function () {
            if (classInfoList.length === 1) {
                selClassInfoIndexList[0] = classInfoList[0];
            }
            if (selClassInfoIndexList.length !== 1) {
                layer.msg("请选择");
                return;
            }
            var campus = selClassInfoIndexList[0][0];
            var teacher = selClassInfoIndexList[0][1];
            var time = selClassInfoIndexList[0][2];
            var data = formatClassInfoData[campus][teacher][time];
            admin.popup({
                title: "选课",
                area: ["420px", window.screen.availHeight * 0.9 + "px"],
                id: "LAY-popup-user-elective-confirm",
                success: function(layero, index) {
                    data['teacher'] = data['teachers'].toString();
                    var remark = "";
                    var timeList = data.time;
                    layui.each(timeList, function (index, item) {
                        remark += item.description;
                        if(item.classRoom.toString() !== "") {
                            remark += "-" + item.classRoom.toString();
                        }
                        if (item.remark !== "") {
                            remark += "-" + item.remark;
                        }
                        remark += "<br>";
                    });
                    data['remark'] = remark;
                    view(this.id).render("menu/elective/confirmClass", data).done(function () {
                        form.on("submit(LAY-user-back-submit)",function (formData) {
                            layer.close(index);
                            var load = layer.load(2);
                            var field = formData.field;
                            var content = {};
                            content['classCode'] = data.classCode;
                            content['classNum'] = data.classNum;
                            content['coin'] = $('#coinDiv')[0].textContent;
                            content['buy'] = field.hasOwnProperty("buy");
                            content['retake'] = field.hasOwnProperty("retake");
                            content['adjust'] = field.hasOwnProperty("adjust");
                            $.ajax({
                                url: host + '/jw/stu/course/elective/save',
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify(content),
                                dataType: 'json',
                                complete: function (result) {
                                    layer.close(load);
                                    result = result.responseJSON;
                                    if (result.status === 200) {
                                        layer.msg("选课成功");
                                        layui.sessionData("stuCourse", null);
                                    }else {
                                        layer.msg(result.message);
                                    }
                                }
                            })
                        });
                    });
                }
            });
        });
        // 监听重选
        form.on("submit(refresh)", function (data) {
            selClassInfoIndexList = [];
            drawPersonNum(classInfoList);
            renderTable(classInfoData);
            renderRadio();
            // 隐藏重选按钮
            $('#refreshBtn').hide();
            form.render();
        });

        function transCourseTimeList(courseList) {
            var result = [];
            for (var i = 0; i < courseList.length; i++) {
                var courseTimes = [];
                for (var j = 0; j < courseList[i]["time"].length; j++) {
                    courseTimes.push(courseList[i]["time"][j])
                }
                result.push(courseTimes)
            }
            return result;
        }
        function checkTimeConflict(courseTime, stuCourseTimeList) {
            for (var i = 0; i < stuCourseTimeList.length; i++) {
                var weeks = courseTime["weeks"];
                for (var j = 0; j < weeks.length; j++) {
                    var anotherWeek = stuCourseTimeList[i]["weeks"];
                    if (anotherWeek.includes(weeks[j])) {
                        if (courseTime["day"] === stuCourseTimeList[i]["day"]) {
                            var lesson = courseTime["lesson"];
                            for (var k = 0; k < lesson.length; k++) {
                                if (stuCourseTimeList[i]["lesson"].includes(lesson[k])) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
            return false;
        }
        function getTimeConflict(stuCourseList, courseList) {
            var stuCourseTimeList = [];
            for (var i = 0; i < stuCourseList.length; i++) {
                for (var j = 0; j < stuCourseList[i]["time"].length; j++) {
                    stuCourseTimeList.push(stuCourseList[i]["time"][j])
                }
            }
            var courseTimeList = transCourseTimeList(courseList);
            var result = [];
            for (i = 0; i < courseTimeList.length; i++) {
                var add = false;
                for (j = 0; j < courseTimeList[i].length; j++) {
                    var conflict = checkTimeConflict(courseTimeList[i][j], stuCourseTimeList);
                    if (conflict) {
                        result.push(conflict);
                        add = true;
                        break;
                    }
                }
                if (!add) result.push(false)
            }
            return result;
        }
        function getPersonNumConflict(classInfos) {
            var personNumConflict = [];
            for (var i = 0; i< classInfos.length; i++) {
                personNumConflict.push(classInfos[i]["limitNum"] <= classInfos[i]["determineNum"])
            }
            return personNumConflict;
        }
        function getConflictList(stuCourseList, courseList) {
            var timeConflict = getTimeConflict(stuCourseList, courseList);
            var personNumConflict = getPersonNumConflict(courseList);
            var conflictList = [];
            for (var i = 0; i <  courseList.length; i++) {
                conflictList.push(timeConflict[i] || personNumConflict[i])
            }
            return conflictList;
        }

        // 监听筛除按钮
        form.on("submit(screening)", function () {
            var listStr = JSON.stringify(layui.sessionData("stuCourse"));
            if (listStr !== "{}") {
                var stuCourse = JSON.parse(layui.sessionData("stuCourse")['list']);
                afterGetStuCourse(stuCourse);
            }else {
                var load = layer.load(2);
                $.ajax({
                    url: host + "/jw/stu/timetable",
                    complete: function (result) {
                        $('#screening').hide();
                        result = result.responseJSON;
                        if (result['status'] === 200) {
                            layui.sessionData("stuCourse", {key: "list", value: JSON.stringify(result["data"]["courseList"])});
                            afterGetStuCourse(result["data"]["courseList"]);
                            layer.close(load);
                        }else {
                            layer.msg(result['message'])
                        }
                    }
                })
            }
        });

        function afterGetStuCourse(stuCourse) {
            var conflictList = getConflictList(stuCourse, classInfoData);
            var newClassData = [];
            for(i = 0; i < classInfoData.length; i++) {
                if (!conflictList[i]) {
                    newClassData.push(classInfoData[i])
                }
            }
            classInfoData = newClassData;
            formatClassInfoData = parseClassList(classInfoData);
            renderTable(classInfoData);
            renderRadio();
            $('#screening').hide();
        }

        // 人数画图
        function drawPersonNum(classinfos) {
            var classlist = [];
            var limitNums = [];
            var nowNums = [];
            var determineNums = [];
            for(var index in classinfos) {
                var campus = classinfos[index][0];
                var teacher = classinfos[index][1];
                var time = classinfos[index][2];
                classlist.push(campus  + "." + teacher + "--" + time);
                var limitNum = formatClassInfoData[campus][teacher][time].limitNum;
                var nowNum = formatClassInfoData[campus][teacher][time].nowNum;
                var determineNum = formatClassInfoData[campus][teacher][time].determineNum;
                limitNums.push(limitNum);
                nowNums.push(nowNum);
                determineNums.push(determineNum);
            }
            
            // 根据数量和宽度判断变成折线图还是柱状图
            var width = window.screen.availWidth;
            var type = "line";
            if (classinfos.length <= 8 && width > 800) {
                type = "bar";
            }


            // 是否有滑动条,以及显示多少数据
            var len = 100;
            var slide = false;
            if (classinfos.length >= 20 || width < 1000) {
                slide = true;
                var num = parseInt(width / 100 * 1.2);
                len = parseInt(num / classinfos.length * 100);
            }

            if (classinfos.length === 1) {
                type = "bar";
                slide = false;
            }

            var personData = {
                title: {
                    text: decodeURI(classname),
                    textAlign: "auto",
                    textStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: "axis",
                    formatter: function(data)
                    {
                        var teacher = data[0].name.split(".")[1].split("--")[0] + "</br>";

                        var timeStart = data[0].name.indexOf("--");
                        var time = data[0].name.substr(timeStart + 2);
                        var timeList = time.split(",");
                        var timeDescription = "";
                        timeList.forEach(function (time) {
                            timeDescription += time + "</br>";
                        });

                        var personDescription = "";
                        data.forEach(function (classData) {
                            personDescription += classData.seriesName + "：" + classData.data + "</br>"
                        });

                        return teacher + timeDescription + personDescription;
                    }
                },
                legend: {
                    type: "scroll",
                    data: ["限选", "已选", "确定"]
                },
                xAxis: [{
                    type: "category",
                    boundaryGap: true,
                    axisLabel : {
                        interval:0,
                        rotate:20,
                        formatter : function(params){
                            var index = params.indexOf("--");
                            var str = params.substr(0, index);
                            if (str.length > 11) {
                                return str.substr(0, 10) + ".."
                            }
                            return str;
                        }

                    },
                    data: classlist
                }],
                yAxis: [{
                    type: "value"
                }],
                series: [{
                    name: "限选",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: limitNums
                }, {
                    name: "已选",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: nowNums
                },{
                    name: "确定",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: determineNums
                }],
                dataZoom:{
                    type: 'slider',
                    show: slide,
                    height:10,//滚动条高度
                    start:0,//滚动条开始位置（共100等份）
                    end: len//结束位置（共100等份）
                }
            };
            var card= document.getElementById('LAY-index-dataview');
            var myChart = echarts.init(card, layui.echartsTheme);
            myChart.setOption(personData);
            myChart.resize();
        }

        function renderTable(classInfoData) {
            if (tableln === undefined) {
                tableln = table.render({
                    elem: '#test-table-page'
                    ,cols:[[
                        {field:'className', width:200, title:'课程', align:'left'}
                        ,{field:'teacher',  width:200,  title:'教师', align:'left', templet: function (d) { return strs2Str(d['teachers']) }}
                        ,{field:'time', width:320, title:'时间', templet: function (d) {return list2Str(d.time, "description")}}
                        ,{field:'credit', width:60, title:'学分'}
                        ,{field: 'remark', minWidth:200, title:'备注', templet: function (d) { return list2Str(d.time, "remark")}}
                    ]]
                    ,data: classInfoData
                    ,limit: classInfoData.length
                })
            }else {
                tableln.reload({
                    data: classInfoData
                    ,limit: classInfoData.length
                })
            }
        }

    });
</script>